/**
 * 
 */
package com.blogjava.bluedavy.disApp.nio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

/**
 * @author Jun
 *
 */
public class Client {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		
		int port = 9527;

		SocketChannel sc = SocketChannel.open();
		sc.configureBlocking(false);
		
		sc.connect(new InetSocketAddress("localhost",port));
		Selector selector = Selector.open();
		sc.register(selector, SelectionKey.OP_CONNECT);
		
		BufferedReader systemIn = new BufferedReader(new InputStreamReader(System.in));
		
		while (true) {		
			
				if(sc.isConnected()){
					
					String cmd = systemIn.readLine();
					sc.write(Charset.forName("UTF-8").encode(cmd));
					
					if(cmd == null || "quit".equalsIgnoreCase(cmd.trim())){
						
						systemIn.close();
						sc.close();
						selector.close();
						System.out.println("Client quit !");
						System.exit(0);
						
					}									
				}
				
				int nKeys = selector.select(1000);
				if(nKeys >0 ){
					for (SelectionKey key : selector.keys()) {
						
						if(key.isConnectable()){
							
							SocketChannel sc2 = (SocketChannel)key.channel();
							sc2.configureBlocking(false);
							sc2.register(selector, SelectionKey.OP_READ);
							sc2.finishConnect();
							
						}
						else if (key.isReadable()) {
							
							ByteBuffer buffer = ByteBuffer.allocate(1024);
							SocketChannel sc2 = (SocketChannel)key.channel();
							int readBytes = 0;
							
							try {
								int ret = 0;
								try {
									while ((ret = sc2.read(buffer)) > 0) {
										readBytes += ret;
									}
								} finally {
									// TODO: handle exception
									buffer.flip();
								}
								if(readBytes>0){
									
									System.out.println(Charset.forName("UTF-8").decode(buffer).toString());
									buffer = null;
									
								}
								
								
							} finally {
								// TODO: handle exception
								if(buffer != null)
									buffer.clear();
							}
							
							
							
						}	
					}	
				}
				

				
			}
		}
		
		
	}


